<?php

namespace English\Controller;

use Think\Controller;

class AccountController extends BaseController
{
    /**
     * 页面显示
     */
    public function index()
    {
        //用户id
        $user_id = session('index_user_id');

        //获取用户信息
        $userData = M('user')->where(['id' => $user_id])->find();
        $this->assign('userData', $userData);

        if (empty($userData['headimg'])) {
            $avatar = '/Public/Front/images/tx.jpg';
        } else {
            $avatar = $userData['headimg'];
        }
        $this->assign('avatar', $avatar);

        $this->display();
    }

    /**
     * 联系客服
     * User: ming
     * Date: 2019/11/21 11:44
     */
    public function kefu()
    {
        if (IS_POST) {
            $param = I('post.');
            if ($param['title'] == '' || $param['content'] == '' || $param['img'] == '' || $param['phone'] == '') {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'Please enter the complete information to submit!'));
            }
            $param['time'] = time();
            $param['user_id'] = session('index_user_id');
            if (M('message')->add($param)) {
                $this->ajaxReturn(array('code' => '1', 'message' => 'Submitted successfully!'));
            } else {
                $this->ajaxReturn(array('code' => '1', 'message' => 'Resubmit!'));
            }

        }
        $user_id = session('index_user_id');
        $num = M('message')->where(['user_id' => $user_id, 'status' => 2, 'is_cha' => 0])->count('id');
        $this->assign('num', $num);
        $this->display();
    }

    /**
     * 回复内容
     * User: ming
     * Date: 2019/11/22 14:46
     */
    public function question()
    {
        $user_id = session('index_user_id');
        $data = M('message')->where(array('user_id' => $user_id))->order('id desc')->select();
        $this->assign('data', $data);

        //点击进去，改变已回复的 信息为 已查看
        //查询已回复和未查看的信息数量
        $click_message = M('message')->where(['user_id' => $user_id, 'status' => 2, 'is_cha' => 0])->select();
        foreach ($click_message as $key => $value) {

            M('message')->where(['id' => $value['id']])->setField('is_cha', 1);
        }
        $this->display();
    }

    public function qrcode()
    {
        $s = $_SERVER['SCRIPT_NAME'];
        $s = substr($s, 0, -9);
        //用户id
        $user_id = session('index_user_id');
        //获取用户信息
        $userData = M('user')->where(['id' => $user_id])->find();
//        $url = "http://" . $_SERVER['SERVER_NAME'] . $s . "front.php/Public/register/username/" . $userData['username'];
        $url = "http://" . $_SERVER['SERVER_NAME'] . $s . "front.php/Public/register/username/" . $userData['invite'];//邀请码
        $this->assign('url', $url);
        $this->assign('userData', $userData);
        $this->display();
    }

    /**
     * 单图上传图片
     */
    public function upload()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Uploads/'; // 设置附件上传根目录
        $upload->savePath = 'header/'; // 设置附件上传（子）目录
        // 上传文件
        $info = $upload->upload();

        dump($info);
        die();

        if (!$info) {
            //上传错误提示错误信息
            $this->ajaxReturn(array('code' => '-1', 'message' => $upload->getError()));
        } else {
            //图片路径
            $path = '/Uploads/' . $info['image']['savepath'] . $info['image']['savename'];

            //用户id
            $user_id = session('index_user_id');
            $data['headimg'] = $path;
            M('admin')->where(['id' => $user_id])->save($data);
            //数据入库
            $this->ajaxReturn(array('code' => '1', 'message' => $path));
        }
    }

    /**
     * 多图上传
     */
    public function forUpload()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Uploads/'; // 设置附件上传根目录
        $upload->savePath = 'card/'; // 设置附件上传（子）目录
        // 上传文件
        $info = $upload->upload();

        if (!$info) {
            //上传错误提示错误信息
            $this->ajaxReturn(array('code' => '-1', 'message' => $upload->getError()));
        } else {
            //图片路径
            $path = '/Uploads/' . $info['file']['savepath'] . $info['file']['savename'];

            //用户id
            //$user_id = session('index_user_id');
            //$data['headimg'] = $path;
            //M('admin')->where(['id'=>$user_id])->save($data);
            //数据入库
            $this->ajaxReturn(array('code' => '1', 'message' => $path));
        }
    }

    /**
     * GBC锁仓
     */
    public function locked()
    {
        //用户id
        $user_id = session('index_user_id');

        //获取当前的gbc价格
        $gbcPriceData = M('market')->where(['coinname' => 'gbc'])->order('id desc')->find();

        //获取平台分红数量
        $map['from_id'] = $user_id;
        $map['reward_type'] = 001;
        $shareData = M('fmoney')->where($map)->sum('amount');
        $shareDataCny = $shareData * $gbcPriceData['pricecny'];
        $shareDataCny = round($shareDataCny, 2);
        $this->assign('shareData', $shareData);
        $this->assign('shareDataCny', $shareDataCny);

        //获取锁仓数量
        $lockData = M('locked')->where(['userid' => $user_id])->sum(amount);
        $lockDataCny = $lockData * $gbcPriceData['pricecny'];
        $lockDataCny = round($lockDataCny, 2);
        $this->assign('lockData', $lockData);
        $this->assign('lockDataCny', $lockDataCny);

        //获取账户信息
        $userData = M('admin')->where(['id' => $user_id])->find();
        $this->assign('userData', $userData);

        $userDataCny = $userData['reward1'] * $gbcPriceData['pricecny'];
        $userDataCny = round($userDataCny, 2);
        $this->assign('userDataCny', $userDataCny);

        //获取分红记录
        $where['owner'] = $user_id;
        $where['reason'] = array('in', '分红');
        $count = M('fmoney')->where($where)->count();
        $Page = new \Think\Page($count, 5);
        $Page->setConfig(prev, 'Previous');
        $Page->setConfig(next, 'Next page');
        $show = $Page->show();
        $data = M('fmoney')->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->order('id desc')->select();
        $this->assign('cashData', $data);
        $this->assign('page', $show);

        //获取btc实时价格
        $btcPrice = M('reward_config')->find();
        $this->assign('btcPrice', $btcPrice['canshu60']);

        $this->display();
    }

    /**
     * 是否认证
     */
    public function iscard()
    {
        //用户id
        $user_id = session('index_user_id');

        //获取用户信息
        $userData = M('user')->where(['id' => $user_id])->find();
        $this->assign('userData', $userData);

        $this->display();
    }

    /**
     * 邀请推广
     */
    public function spread()
    {
        //用户id
        $user_id = session('index_user_id');

        //获取邀请码
        $codeData = M('admin')->where(['id' => $user_id])->find();
        $this->assign('codeData', $codeData);

        $this->display();
    }

    /**
     * 修改密码
     */
    public function change()
    {
        if (IS_POST) {
            $data = I('post.');
            //用户id
            $user_id = session('index_user_id');
            //判断旧密码是否正确
            $userData = M('user')->where(['id' => $user_id])->find();
            //判断信息是否完整
            if ($data['status'] == 2) {
                if (trim($data['password2']) == '' || $data['code'] == '') {
                    $this->ajaxReturn(array('code' => '-1', 'message' => 'Modified information is incomplete'));
                }
                $data['password2'] = md5($data['password2']);
//                if(md5($data['oldpassword']) != $userData['password2'])
//                {
//                    $this->ajaxReturn(array('code'=>'-1','message'=>'旧密码不正确'));
//                }

            } else {
                if (trim($data['newpassword']) == '' || $data['code'] == '') {
                    $this->ajaxReturn(array('code' => '-1', 'message' => 'Modified information is incomplete'));
                }

                //判断两次密码是否一致
                if ($data['newpassword'] != $data['newspassword']) {
                    $this->ajaxReturn(array('code' => '-1', 'message' => 'Two passwords are inconsistent'));
                }
                //			if(md5(md5($data['oldpassword']).$userData['number']) != $userData['passwords'])

                if (md5($data['newpassword']) == $userData['password']) {
                    $this->ajaxReturn(array('code' => '-1', 'message' => 'Please change the new password'));
                }

                $data['password'] = md5($data['newpassword']);

//                if(md5($data['oldpassword']) != $userData['password'])
//                {
//                    $this->ajaxReturn(array('code'=>'-1','message'=>'旧密码不正确'));
//                }
            }

            //验证短信验证码
            $codeData = M('msg_list')->where(['tel' => $userData['mobile']])->order('id desc')->find();
            if ($data['code'] != $codeData['code']) {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'Incorrect verification code'));
            }

//			$number = $this->randomkeys(4);
//            $data['number'] = $number;
//            $data['passwords'] = md5(md5($data['newpassword']).$number);

            $res = M('user')->where(['id' => $user_id])->save($data);
            if ($res) {
                $this->ajaxReturn(array('code' => '1', 'message' => 'Successfully modified'));
            } else {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'fail to edit'));
            }

        } else {
            //用户id
            $user_id = session('index_user_id');

            //获取用户信息
            $userData = M('user')->where(['id' => $user_id])->find();

//            $pos = strpos('@', $userData['username']);

            $exp = "^[a-z'0-9]+([._-][a-z'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";

            if (preg_match($exp, $userData['username'])) { //先用正则表达式验证email格式的有效性
                $userData['type'] = 2;//邮箱

            } else {
                $userData['type'] = 1;//手机号
            }

            $this->assign('userData', $userData);

            $this->display();
        }
    }

    public function getUser(){
        if(IS_POST){
            $data=I('post.');
//           $nickname= M('user')->where(['username'=> $data['name']])->getField('nickname');
//           $nickname= M('user')->where(['username'=> $data['name']])->getField('phone');
//           $nickname= M('user')->where(['username'=> $data['name']])->getField('email');
           $nickname= M('user')->where(['uid'=> $data['name']])->getField('email');
           if($nickname){
               ajax_return(1, $nickname);
           }

        }
        ajax_return(-1, 'Account does not exist');

    }
    /**
     * 互转
     * User: ming
     * Date: 2019/11/25 9:16
     */
    public function withdraw()
    {

        $userid = $this->user_info['id'];
        $userData = M('user')->where(['id' => $userid])->find();
        $config = M('reward_config')->find();
        if (IS_POST) {
//            if ($userData['is_real'] != 2) {
////                $this->ajaxReturn(array('code'=>'-1','message'=>'请先到个人中心完成实名认证'));
//                ajax_return(1, '请先到个人中心完成实名认证');
//            }
            $data = I('post.');
            //验证信息是否完整
            if ($data['coinname'] == '' || $data['account'] == '' || $data['amount'] == '' ) {
                ajax_return(1, 'Incomplete information');
            }
            //短信
            // $code['mobile'] = $data['phone'];
            // $code['code'] = $data['getCode'];
            // if (!M('msg_list')->where($code)->order('id desc')->find()) {
            //     ajax_return(1, '验证码不正确');
            // }
//            $check_msg = check_msg_minute($data['phone'],$data['getCode']);
//            if($check_msg==1){
//            	ajax_return(1, '验证码不正确');
//            }
//            if($check_msg==2){
//            	ajax_return(1, '验证码已失效');
//            }

            //验证支付密码
//            if (md5($data['password']) != $userData['password2']) {
//                ajax_return(1, '支付密码错误');
//            }

            //判断余额是足够
            if ($data['amount'] <= 0) {
                ajax_return(1, 'The quantity cannot be less than or equal to 0');
            }
            if($data['amount'] <$config['p97']){
                ajax_return(1, 'Interchange needs'.$config['p97'].'Spin');
            }
            $amount = 0;//总共扣除币默认为0
            $coin_val = 0;//z值
            if ($data['coinname'] == 2) {
                //ETH2019052117
//                if ($config['ptr78'] > $data['amount'])
//                {
//                    ajax_return(1,'超过最低限额'.$config['ptr78']);
//                }
                //手续费扣除
                $charge = $data['amount'] * $config['p96'];
                $amount = $data['amount'] + $charge;
                $coin_val = '2';
            } elseif ($data['coinname'] == 8) {//USDT
                //USDT2019052117
//                if ($config['ptr79'] > $data['amount']) {
//                    ajax_return(1, '超过最低限额' . $config['ptr79']);
//                }
                //手续费扣除
                $charge = $data['amount'] * $config['p96'];
                $amount = $data['amount'] + $charge;
                $coin_val = '8';
            }  else {
                ajax_return(1, 'This currency cannot be transferred');
            }

            if ($amount > $userData['z' . $coin_val]) {
                ajax_return(1, 'Insufficient account balance');
            }
            $account_list = M('user')->where(['username' => $data['uid']])->find();
            if (!$account_list) {
                ajax_return(1, 'No such account found');
            }
            if ($userid == $account_list['id']) {
                ajax_return(1, 'Can\'t transfer it to myself');
            }
            M()->startTrans();
            $res1 = M('user')->where(['id' => $account_list['id']])->setInc('z' . $coin_val, $data['amount']);//增加原数
            $res2 = M('user')->where(['id' => $userid])->setDec('z' . $coin_val, $amount);//减少+手续费
//            $res3 = $this->add_log($account_list['id'],$userid , $data['amount'], $coin_val, '转出', 1, $config['p96']);
//            $res4 = $this->add_log($userid ,$account_list['id'], $data['amount'], $coin_val, '转入', 2, $config['p96']);

            $res3 = $this->add_fmoney_log($account_list['id'],$userid , $amount, $coin_val, 'Roll out',  "18", $config['p96']);
            $res4 = $this->add_fmoney_log($userid ,$account_list['id'], $data['amount'], $coin_val, 'Transfer into',  "18", $config['p96']);
            if ($res1 && $res2 && $res3 && $res4) {
                M()->commit();
                ajax_return(0, 'Successful transfer');
            } else {
                M()->rollback();
                ajax_return(1, 'Transfer failed');
            }

        } else {
            $exp = "^[a-z'0-9]+([._-][a-z'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";
            if (preg_match($exp, $userData['username'])) { //先用正则表达式验证email格式的有效性
                $userData['type'] = 2;//邮箱
            } else {
                $userData['type'] = 1;//手机号
            }
            //获取账户信息
            $this->assign('userData', $userData);
            //判断是否生成钱包地址ASSET
            $this->assign('accountBalance', $userData['z8']);
            //默认 查询usdt最大全部可转 2020 11 26
            $this->assign('max', floor($userData['z8']/(1+$config['p96'])));
            $this->assign('config', $config);
            $this->assign('sxf', $config['p96'] * 100);
            $this->display();
        }
    }

    public function add_coin_log($openid,$owner,$tot_money,$type,$reason,$reward_type,$list_id=0,$price=0){
        $fmoney['from_id'] = $openid;
        $fmoney['user_id'] = $owner;
        $fmoney['amount'] = $tot_money;
        $fmoney['create_time'] = time();
        $fmoney['type'] = $type;
        $fmoney['reward_type'] = $reward_type;
        $fmoney['tips'] = $reason;
        $fmoney['list_id'] = $list_id;
        $fmoney['price'] = $price;

        $data = M('fmoney')->add($fmoney);
        return $data;
    }

    /**
     * 身份认证
     */
    public function card()
    {
        if (IS_POST) {
            $data = I('post.');

            //用户id
            $user_id = session('index_user_id');

            if ($data['truename'] == '' || $data['cardnumber'] == '' || $data['faceimage'] == '' || $data['backimage'] == '' || $data['handimage'] == '') {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'Incomplete upload information'));
            }

            //验证身份证号
            $res1 = $this->is_idcard($data['cardnumber']);

            if (!$res1) {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'ID number is incorrect'));
            }

            $condition['id_card'] = $data['cardnumber'];
            $condition['is_real'] = ['in', [1, 2]];//审核中通过的会判断

            $card = M('user')->where($condition)->find();
            if (!empty($card)) {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'ID number is already bound'));
            }

            $info['truename'] = $data['truename'];
            $info['id_card'] = $data['cardnumber'];
            $info['card_face'] = $data['faceimage'];
            $info['card_back'] = $data['backimage'];
            $info['card_hand'] = $data['handimage'];
            $info['is_real'] = 1;

            $res2 = M('user')->where(['id' => $user_id])->save($info);

            if ($res2) {
                $this->ajaxReturn(array('code' => '1', 'message' => 'Uploaded successfully'));
            } else {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'upload failed'));
            }

        } else {
            $this->display();
        }

    }

    /**
     * 邀请人管理
     */
    public function invite()
    {
        //用户id
        $user_id = session('index_user_id');

        //获取一级邀请人
        $map1['higher_id'] = $user_id;
        $map1['level'] = 1;
        $oneLevel = M('admin_tj')->where($map1)->select();

        //获取用户信息和锁仓数量

        foreach ($oneLevel as $k => $v) {
            $res1 = M('admin')->where(['id' => $v['admin_id']])->find();
            $v['usernames'] = $res1['usernames'];
            $v['addtime'] = $res1['time'];
            $oneLevelData[] = $v;
        }
        $this->assign('oneLevelData', $oneLevelData);

        //获取二级邀请人

        $map2['higher_id'] = $user_id;
        $map2['level'] = 2;
        $twoLevel = M('admin_tj')->where($map2)->select();

        //获取用户信息和锁仓数量

        foreach ($twoLevel as $k => $v) {
            $res2 = M('admin')->where(['id' => $v['admin_id']])->find();
            $v['usernames'] = $res2['usernames'];
            $v['addtime'] = $res2['time'];
            $twoLevelData[] = $v;
        }
        $this->assign('twoLevelData', $twoLevelData);

        //获取三级邀请人

        $map3['higher_id'] = $user_id;
        $map3['level'] = 3;
        $threeLevel = M('admin_tj')->where($map3)->select();

        //获取用户信息和锁仓数量

        foreach ($threeLevel as $k => $v) {
            $res3 = M('admin')->where(['id' => $v['admin_id']])->find();
            $v['usernames'] = $res3['usernames'];
            $v['addtime'] = $res3['time'];
            $threeLevelData[] = $v;
        }
        $this->assign('threeLevelData', $threeLevelData);

        $this->display();
    }

    /**
     * 安全中心
     */
    public function security()
    {
        $this->display();
    }

    /**
     * 手机验证
     */
    public function sms()
    {
        if (IS_POST) {
            $data = I('post.');

            //用户id
            $user_id = session('index_user_id');

            //验证信息是否完整
            if ($data['password'] == '' || $data['mobile'] == '' || $data['code'] == '') {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'Verification information is incomplete'));
            }

            //验证密码是不否正确
            $userData = M('admin')->where(['id' => $user_id])->find();
            if (md5(md5($data['password']) . $userData['number']) != $userData['passwords']) {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'Incorrect login password'));
            }

            //验证短信验证码
            $codeData = M('msg_list')->where(['tel' => $data['mobile']])->order('id desc')->find();
            if ($data['code'] != $codeData['code']) {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'Incorrect verification code'));
            } else {
                $this->ajaxReturn(array('code' => '1', 'message' => 'Successful verification'));
            }
        } else {
            //用户id
            $user_id = session('index_user_id');

            //获取用户信息
            $userData = M('admin')->where(['id' => $user_id])->find();
            $this->assign('userData', $userData);

            $this->display();
        }

    }

    /*
     * 换绑手机号
     */
    public function mobile()
    {
        if (IS_POST) {
            $data = I('post.');

            //用户id
            $user_id = session('index_user_id');

            //验证信息是否完整
            if ($data['password'] == '' || $data['mobile'] == '' || $data['code'] == '') {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'Incomplete binding information'));
            }

            //验证密码是不否正确
            $userData = M('admin')->where(['id' => $user_id])->find();
            if (md5(md5($data['password']) . $userData['number']) != $userData['passwords']) {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'Incorrect login password'));
            }

            //验证短信验证码
            $codeData = M('msg_list')->where(['tel' => $data['mobile']])->order('id desc')->find();
            if ($data['code'] != $codeData['code']) {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'Incorrect verification code'));
            }

            //验证手机号
            if (!preg_match("/^1[345789]{1}\d{9}$/", $data['mobile'])) {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'Please enter the correct phone number'));
            }

            //验证手机号是否存在
            $usernames = M('admin')->where('mobile = "' . $data['mobile'] . '" ')->find();
            if (!empty($usernames)) {
                $this->ajaxReturn(array('code' => '-1', 'message' => 'Phone number already exists'));
            }

            $info['mobile'] = $data['mobile'];

            $res = M('admin')->where(['id' => $user_id])->save($info);

            if ($res) {
                $this->ajaxReturn(array('code' => '1', 'message' => 'Bind successfully'));
            } else {
                $this->ajaxReturn(array('code' => '1', 'message' => 'Binding failed'));
            }

        } else {

            $this->display();
        }

    }


    /**
     * 关于我们
     */
    public function about()
    {
        $company = M('news')->where(['title' => 'about us'])->find();
        $this->assign('company', $company);
        $this->display();
    }


    /**
     * 系统设置
     */
    public function system()
    {
        $this->display();
    }

    /**
     * 推荐详情
     */
    public function detail()
    {
        //用户id
        $user_id = session('index_user_id');

        //获取锁仓记录
        $where['owner'] = $user_id;
        $where['reason'] = 'Referral Award';
        $count = M('fmoney')->where($where)->count();
        $Page = new \Think\Page($count, 8);
        $Page->setConfig(prev, 'Previous');
        $Page->setConfig(next, 'Next page');
        $show = $Page->show();
        $data = M('fmoney')->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->order('id desc')->select();
        $this->assign('detailData', $data);
        $this->assign('page', $show);

        $this->display();
    }

    /**
     * 语言设置
     */
    public function language()
    {
        $this->display();
    }

    public function languageDetail()
    {
        $this->display();
    }

    public function directDetail()
    {
        $this->display();
    }

    public function singelAchievement()
    {
        $this->display();
    }

    public function teamAchievement()
    {
        $this->display();
    }

}